import { Injectable } from '@nestjs/common';
import { CreateGymnasiumDto } from './dto/create-gymnasium.dto';
import { UpdateGymnasiumDto } from './dto/update-gymnasium.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Gymnasium } from './entities/gymnasium.entity';

@Injectable()
export class GymnasiumService {
  constructor(
    @InjectRepository(Gymnasium)
    private repository: Repository<Gymnasium>,
  ) {}
  async create(createGymnasiumDto: CreateGymnasiumDto) {
    const entity = this.repository.create(createGymnasiumDto);
    return await this.repository.save(entity);
  }

  async bindTournament(gid: number, tid: number) {
    const entity = this.repository.create({
      id: gid,
      tournaments: [{ id: tid }],
    });
    return await this.repository.save(entity);
  }

  async getByTournamentId(tid: number){
    return this.repository
      .createQueryBuilder('gymnasium')
      .leftJoinAndSelect('gymnasium.playgrounds', 'playgrounds')
      .leftJoinAndSelect('gymnasium.tournaments', 'tournaments')
      .where('tournaments.id = :tid', { tid })
      .getMany();
  }

  async findAll() {
    return await this.repository.find({
      order: {
        createTime: 'DESC',
      },
    });
  }

  async findOne(id: number) {
    const res = await this.repository.findOne({ where: { id } });
    return res;
  }

  async update(id: number, updateGymnasiumDto: UpdateGymnasiumDto) {
    await this.repository.update(id, updateGymnasiumDto);
    return await this.repository.find({ where: { id } });
  }

  async remove(id: number) {
    return await this.repository.delete(id);
  }
}
